<template>
	<v-dialog
		:title="title"
		width="1100px"
		:close-on-click-modal="false"
		v-model="visible"
	>
		<el-steps
			:active="step"
			finish-status="success"
			simple
			style="margin-left: -20px; margin-right: -20px; margin-bottom: 10px"
		>
			<el-step title="租户基本信息"></el-step>
			<el-step title="创建租户管理员"></el-step>
			<el-step title="设置访问权限"></el-step>
			<el-step title="配置产品信息"></el-step>
		</el-steps>
		<el-form
			v-show="step === 0"
			height="600px"
			:model="inputForm"
			ref="basicForm"
			v-loading="loading"
			:class="method === 'view' ? 'readonly' : ''"
			:disabled="method === 'view'"
			label-width="120px"
		>
			<el-form-item label="租户颜色" prop="basicForm.color">
				<el-color-picker
					:predefine="[
						'#ff4500',
						'#ff8c00',
						'#ffd700',
						'#90ee90',
						'#00ced1',
						'#1e90ff',
						'#c71585',
						'#c7158577',
					]"
					v-model="inputForm.basicForm.color"
				></el-color-picker>
			</el-form-item>
			<el-form-item
				label="租户名称"
				prop="basicForm.name"
				:rules="[
					{
						required: true,
						message: '租户名称不能为空',
						trigger: 'blur',
					},
					{ validator: validateNameExist, trigger: 'blur' },
				]"
			>
				<el-input
					v-model="inputForm.basicForm.name"
					placeholder="请填写租户名称"
				></el-input>
			</el-form-item>
			<el-form-item
				label="绑定域名"
				prop="basicForm.domain"
				:rules="[
					{
						required: true,
						message: '绑定域名不能为空',
						trigger: 'blur',
					},
					{ validator: validateDomainExist, trigger: 'blur' },
				]"
			>
				<el-input
					v-model="inputForm.basicForm.domain"
					placeholder="域名不能为空"
				></el-input>
				<el-alert type="success" class="m-t-5"
					>域名可以是ip，也可以是一级或者二级域名，但是不能包含协议头或者端口号，例如:
					127.0.0.1， jeeplus.org, test.jeeplus.org都是允许的,
					如果你不能确定网站的域名是什么，可以在打开该网站时在浏览器控制台通过location.hostname获取域名。如果你访问的域名没有匹配任何租户，那么将指向默认租户。</el-alert
				>
			</el-form-item>
			<el-form-item label="租户开始日期" prop="basicForm.beginDate">
				<el-date-picker
					v-model="inputForm.basicForm.beginDate"
					type="datetime"
					style="width: 100%"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="不填写表示租户立即生效"
				></el-date-picker>
			</el-form-item>
			<el-form-item label="租户结束日期" prop="basicForm.endDate">
				<el-date-picker
					v-model="inputForm.basicForm.endDate"
					type="datetime"
					style="width: 100%"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="不填写表示租户永久有效"
				></el-date-picker>
			</el-form-item>
			<el-form-item
				label="是否可用"
				prop="basicForm.status"
				:rules="[
					{
						required: true,
						message: '租户状态不能为空',
						trigger: 'blur',
					},
				]"
			>
				<el-radio-group v-model="inputForm.basicForm.status">
					<el-radio
						v-for="item in $dictUtils.getDictList('yes_no')"
						:value="item.value"
						:key="item.id"
						>{{ item.label }}</el-radio
					>
				</el-radio-group>
			</el-form-item>
		</el-form>
		<el-form
			v-show="step === 1"
			height="600px"
			:model="inputForm"
			ref="userForm"
			v-loading="loading"
			:class="method === 'view' ? 'readonly' : ''"
			:disabled="method === 'view'"
			label-width="120px"
		>
			<el-form-item label="账号" prop="userForm.loginName">
				<el-input
					v-model="inputForm.userForm.loginName"
					:disabled="true"
					maxlength="50"
					placeholder=""
				></el-input>
			</el-form-item>
			<el-form-item
				label="密码:"
				prop="userForm.newPassword"
				:rules="
					inputForm.userForm.edit
						? []
						: [
								{
									required: true,
									message: '密码不能为空',
									trigger: 'blur',
								},
						  ]
				"
			>
				<el-input
					v-model="inputForm.userForm.newPassword"
					maxlength="50"
					placeholder="若不修改，请留空"
					show-password
				></el-input>
			</el-form-item>
			<el-form-item
				label="确认密码"
				prop="userForm.confirmNewPassword"
				:rules="
					inputForm.userForm.edit
						? []
						: [
								{
									validator: validatePass2,
									trigger: 'blur',
								},
								{
									required: true,
									message: '确认密码不能为空',
									trigger: 'blur',
								},
						  ]
				"
			>
				<el-input
					v-model="inputForm.userForm.confirmNewPassword"
					maxlength="50"
					placeholder=""
					show-password
				></el-input>
			</el-form-item>
			<el-form-item
				label="姓名"
				prop="userForm.name"
				:rules="[
					{
						required: true,
						message: '姓名不能为空',
						trigger: 'blur',
					},
				]"
			>
				<el-input
					v-model="inputForm.userForm.name"
					maxlength="50"
					placeholder=""
				></el-input>
			</el-form-item>
			<el-form-item
				label="手机"
				prop="userForm.mobile"
				:rules="[{ validator: validator.isMobile, trigger: 'blur' }]"
			>
				<el-input
					v-model="inputForm.userForm.mobile"
					maxlength="50"
					placeholder=""
				></el-input>
			</el-form-item>
			<el-form-item
				label="电话"
				prop="userForm.phone"
				:rules="[{ validator: validator.isPhone, trigger: 'blur' }]"
			>
				<el-input
					v-model="inputForm.userForm.phone"
					maxlength="50"
					placeholder=""
				></el-input>
			</el-form-item>
			<el-form-item
				label="邮箱"
				prop="userForm.email"
				:rules="[
					{
						type: 'email',
						message: '请输入正确的邮箱地址',
						trigger: 'blur',
					},
				]"
			>
				<el-input
					v-model="inputForm.userForm.email"
					maxlength="50"
					placeholder=""
				></el-input>
			</el-form-item>
		</el-form>
		<el-form
			v-show="step === 2"
			height="600px"
			:model="inputForm"
			ref="roleForm"
			v-loading="loading"
			:class="method === 'view' ? 'readonly' : ''"
			:disabled="method === 'view'"
			label-width="200px"
		>
			<el-form-item
				label="租户管理员角色名:"
				prop="roleForm.name"
				:rules="[
					{
						required: true,
						message: '请输入租户管理角色名',
						trigger: 'blur',
					},
				]"
			>
				<el-input
					v-model="inputForm.roleForm.name"
					maxlength="50"
					placeholder="请输入租户管理角色名"
				></el-input>
			</el-form-item>
			<el-form-item
				label="租户管理员角色英文名:"
				prop="roleForm.enName"
				:rules="[
					{
						required: true,
						message: '请输入租户管理角色英文名',
						trigger: 'blur',
					},
				]"
			>
				<el-input
					v-model="inputForm.roleForm.enName"
					:disabled="true"
					maxlength="50"
					placeholder=""
				></el-input>
			</el-form-item>
			<el-form-item label="菜单:" prop="roleForm.menuList">
				<el-tree
					:data="menuList"
					:props="{
						label: 'name',
						children: 'children',
					}"
					node-key="id"
					ref="menuListTree"
					:default-expanded-keys="['1']"
					:default-checked-keys="menuCheckedKeys"
					show-checkbox
				>
				</el-tree>
			</el-form-item>
		</el-form>
		<el-form
			v-show="step === 3"
			height="600px"
			:model="inputForm"
			ref="configForm"
			v-loading="loading"
			:class="method === 'view' ? 'readonly' : ''"
			:disabled="method === 'view'"
			label-width="120px"
			class="tenant"
		>
			<el-form-item label="产品标题">
				<el-input v-model="inputForm.configForm.productName"></el-input>
			</el-form-item>
			<el-form-item label="产品logo">
				<image-select
					v-model="inputForm.configForm.logo"
					title="产品logo"
				></image-select>
			</el-form-item>
			<el-form-item label="主题模式">
				<el-radio-group v-model="inputForm.configForm.defaultTheme">
					<div class="setting-layout-drawer">
						<el-radio-button value="default">
							<img
								class="thumbnail-layout"
								src="~@/assets/img/assets-setting-light.svg"
							/>
						</el-radio-button>
					</div>
					<div class="setting-layout-drawer">
						<el-radio-button value="dark"
							><img
								class="thumbnail-layout"
								src="~@/assets/img/assets-setting-dark.svg"
						/></el-radio-button>
					</div>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="导航布局">
				<el-radio-group v-model="inputForm.configForm.defaultLayout">
					<div class="setting-layout-drawer">
						<el-radio-button value="default"
							><img
								class="thumbnail-layout"
								src="~@/assets/img/layout/classic.png"
						/></el-radio-button>
					</div>
					<div class="setting-layout-drawer">
						<el-radio-button value="left"
							><img
								class="thumbnail-layout"
								src="~@/assets/img/layout/left.png"
						/></el-radio-button>
					</div>
					<div class="setting-layout-drawer">
						<el-radio-button value="mix"
							><img
								class="thumbnail-layout"
								src="~@/assets/img/mix.png"
						/></el-radio-button>
					</div>
					<div class="setting-layout-drawer">
						<el-radio-button value="top"
							><img
								class="thumbnail-layout"
								src="~@/assets/img/top.png"
						/></el-radio-button>
					</div>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="主题色">
				<el-radio-group
					v-model="inputForm.configForm.defaultColor"
					size="large"
				>
					<el-tooltip
						effect="dark"
						:content="item.key"
						placement="top-start"
						v-for="(item, index) in colorList"
						:key="index"
					>
						<el-radio-button
							:color="item.color"
							:value="item.color"
							class="setting-layout-color-group"
						>
							<div
								class="color-container"
								:style="`background:${item.color}`"
							></div>
						</el-radio-button>
					</el-tooltip>

					<div class="setting-layout-drawer" style="margin-left: 5px">
						<el-color-picker
							v-model="colorPrimary"
						></el-color-picker>
					</div>
				</el-radio-group>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button :disabled="step === 0" @click="prev"
					>上一步</el-button
				>
				<el-button :disabled="step === 3" @click="next"
					>下一步</el-button
				>
				<el-button @click="visible = false" icon="circle-close"
					>关闭</el-button
				>
				<el-button
					v-if="method != 'view'"
					:disabled="step !== 3"
					type="primary"
					icon="circle-check"
					@click="doSubmit()"
					>确定</el-button
				>
			</span>
		</template>
	</v-dialog>
</template>

<script>
import tenantService from "@/api/sys/tenantService";
import menuService from "@/api/sys/menuService";
export default {
	data() {
		return {
			title: "",
			method: "",
			visible: false,
			loading: false,
			step: 0,
			menuList: [],
			menuCheckedKeys: [],
			colorList: [
				{
					key: "深湖蓝（默认）",
					color: "#2d8cf0",
					label: "0",
				},
				{
					key: "明青",
					color: "#1ba2c0",
					label: "1",
				},
				{
					key: "薄暮",
					color: "#F5222D",
					label: "2",
				},
				{
					key: "火山",
					color: "#FA541C",
					label: "3",
				},
				{
					key: "日暮",
					color: "#FAAD14",
					label: "4",
				},
				{
					key: "橄榄绿",
					color: "#16b2a3",
					label: "5",
				},
				{
					key: "咖啡色",
					color: "#9a7b71",
					label: "6",
				},
				{
					key: "极客蓝",
					color: "#2F54EB",
					label: "7",
				},
				{
					key: "酱紫",
					color: "#722ED1",
					label: "8",
				},
				{
					key: "天空蓝",
					color: "#3e8df7",
					label: "9",
				},
				// {
				//   key: '咖啡色', color: '#9a7b71'
				// },
				// {
				//   key: '深湖蓝', color: '#07b2d3'
				// },
				// {
				//   key: '原谅绿', color: '#0cc26c'
				// },
				// {
				//   key: '古铜灰', color: '#757575'
				// },
				// {
				//   key: '珊瑚紫', color: '#6779fa'
				// },
				// {
				//   key: '橙黄', color: '#eb6607'
				// },
				// {
				//   key: '粉红', color: '#f74584'
				// },
				// {
				//   key: '青紫', color: '#9463f7'
				// },
				// {
				//   key: '橄榄绿', color: '#16b2a3'
				// }
			],
			initForm: null,
			inputForm: {
				basicForm: {
					id: "",
					name: "",
					code: "",
					color: "",
					beginDate: "",
					endDate: "",
					status: "",
					domain: "",
					oldName: "",
					oldCode: "",
					oldDomain: "",
				},
				userForm: {
					loginName: "admin", // 登录名
					name: "", // 姓名
					email: "", // 邮箱
					phone: "", // 电话
					mobile: "", // 手机
					newPassword: "", // 新密码
					confirmNewPassword: "",
					edit: false,
				},
				roleForm: {
					name: "租户管理员",
					enName: "sys",
					menuIds: "",
				},
				configForm: {
					defaultTheme: "",
					defaultColor: "#1890FF",
					productName: "",
					logo: "",
					defaultLayout: "",
				},
			},
		};
	},
	created() {
		this.initForm = JSON.stringify(this.inputForm);
	},
	methods: {
		init(method, id) {
			this.method = method;
			this.inputForm = JSON.parse(this.initForm);
			this.inputForm.basicForm.id = id;
			if (method === "add") {
				this.title = `新建租户`;
			} else if (method === "edit") {
				this.title = "修改租户";
			} else if (method === "view") {
				this.title = "查看租户";
			}
			this.visible = true;
			this.loading = false;
			this.step = 0;
			this.$nextTick(() => {
				this.$refs.menuListTree.setCheckedKeys([]);
				this.inputForm.basicForm.oldName = "";
				this.inputForm.basicForm.oldCode = "";
				menuService
					.treeData({
						isShowHide: 1,
					})
					.then((data) => {
						this.menuList = data;
					});
				if (method === "edit" || method === "view") {
					// 修改或者查看
					this.loading = true;
					tenantService
						.queryById(this.inputForm.basicForm.id)
						.then((data) => {
							this.inputForm = this.recover(this.inputForm, data);
							this.$refs.menuListTree.setCheckedKeys(
								data.roleForm.menuIds.split(",")
							);
							this.inputForm.basicForm.oldName =
								data.basicForm.name;
							this.inputForm.basicForm.oldCode =
								data.basicForm.code;
							this.inputForm.basicForm.oldDomain =
								data.basicForm.domain;
							this.loading = false;
						});
				}
			});
		},
		// 上一步
		prev() {
			if (this.step > 0) this.step--;
		},
		// 下一步
		next() {
			if (this.step === 0) {
				this.$refs["basicForm"].validate((valid) => {
					if (valid) {
						this.step++;
					}
				});
			} else if (this.step === 1) {
				this.$refs["userForm"].validate((valid) => {
					if (valid) {
						this.step++;
					}
				});
			} else if (this.step === 2) {
				this.$refs["roleForm"].validate((valid) => {
					if (valid) {
						this.step++;
						this.inputForm.roleForm.menuIds =
							this.$refs.menuListTree
								.getCheckedKeys()
								.concat(
									this.$refs.menuListTree.getHalfCheckedKeys()
								)
								.join(",");
					}
				});
			}
		},

		handleAvatarSuccess(res) {
			this.inputForm.configForm.logo = res.url;
		},
		validateDomainExist(rule, value, callback) {
			if (
				this.inputForm.basicForm.oldDomain === "" ||
				this.inputForm.basicForm.oldDomain !==
					this.inputForm.basicForm.domain
			) {
				tenantService
					.validateNotExist({
						domain: this.inputForm.basicForm.domain,
					})
					.then((data) => {
						if (data === true) {
							callback();
						} else {
							callback(new Error("域名已存在!"));
						}
					});
			} else {
				callback();
			}
		},
		validateNameExist(rule, value, callback) {
			if (
				this.inputForm.basicForm.name === "" ||
				this.inputForm.basicForm.oldName !==
					this.inputForm.basicForm.name
			) {
				tenantService
					.validateNotExist({ name: this.inputForm.basicForm.name })
					.then((data) => {
						if (data === true) {
							callback();
						} else {
							callback(new Error("租户名称已存在!"));
						}
					});
			} else {
				callback();
			}
		},
		validateCodeExist(rule, value, callback) {
			if (
				this.inputForm.basicForm.oldCode === "" ||
				this.inputForm.basicForm.oldCode !==
					this.inputForm.basicForm.code
			) {
				tenantService
					.validateNotExist({ code: this.inputForm.basicForm.code })
					.then((data) => {
						if (data === true) {
							callback();
						} else {
							callback(new Error("租户编码已存在!"));
						}
					});
			} else {
				callback();
			}
		},
		validatePass2(rule, value, callback) {
			if (value !== this.inputForm.userForm.newPassword) {
				callback(new Error("两次输入密码不一致!"));
			} else {
				callback();
			}
		},
		beforeAvatarUpload(file) {
			const isJPG = file.type.indexOf("image/") >= 0;
			const isLt2M = file.size / 1024 / 1024 < 2;

			if (!isJPG) {
				this.$message.error("上传LOGO只能是图片格式!");
				return false;
			}
			if (!isLt2M) {
				this.$message.error("上传LOGO大小不能超过 2MB!");
				return false;
			}
			return true;
		},
		// 表单提交
		doSubmit() {
			this.$refs["configForm"].validate((valid) => {
				if (valid) {
					this.loading = true;
					tenantService
						.save(this.inputForm)
						.then((data) => {
							this.visible = false;
							this.$message.success(data);
							this.$emit("refreshDataList");
							this.loading = false;
							if (this.$TOOL.data.get("IS_PRIMARY_TENANT")) {
								tenantService.list().then((data) => {
									this.$TOOL.data.set(
										"TENANT_LIST",
										data.records
									);
								});
							}
						})
						.catch(() => {
							this.loading = false;
						});
				}
			});
		},
	},
};
</script>
<style lang="less">
.tenant {
	.setting-layout-color-group {
		.el-radio-button__inner {
			display: inline-flex;
			justify-content: center;
			align-items: center;
			border-radius: 50% !important;
			padding: 3px !important;
		}
	}

	.el-drawer__header {
		padding: 15px;
		border-bottom: 1px solid #e7e7e7;
		border-radius: 2px 2px 0 0;
		margin-bottom: 10px;
	}
	.setting-group-title {
		font-size: 14px;
		line-height: 22px;
		margin: 32px 0 24px 0;
		text-align: left;
		font-style: normal;
		font-weight: 500;
		color: #000000e6;
	}

	.el-form-item__content {
		display: block;
	}

	.setting-container {
		padding: 0px 16px 100px 16px;
		overflow: auto;
		flex: 1;
	}

	.el-radio-group {
		display: inline-flex;
		align-items: center;
		width: fit-content;
	}

	.thumbnail-layout {
		// width: 88px;
		height: 40px;
	}

	.color-container {
		width: 24px;
		height: 24px;
		border-radius: 50%;
		display: inline-block;
	}
	.setting-layout-drawer {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 1px;
	}

	.setting-layout-color-group {
		display: inline-flex;
		width: 36px;
		height: 36px;
		justify-content: center;
		align-items: center;
		border-radius: 50% !important;
		padding: 6px !important;
		border: 2px solid transparent !important;
	}
	.el-radio-button__inner {
		padding: 6px;
	}
	.el-radio-button__original-radio:checked + .el-radio-button__inner {
		background-color: #ffffff !important;
	}
	// .el-radio-button__inner {
	//     border: 2px solid;
	// }

	.el-radio-group.el-size-m {
		min-height: 32px;
		width: 100%;
		height: auto;
		justify-content: space-between;
		align-items: center;
	}

	.setting-layout-drawer {
		display: flex;
		flex-direction: column;
		align-items: center;

		.el-color-picker__trigger {
			border: 1px solid var(--el-color-primary);
			border-radius: 50% !important;
			padding: 3px;
		}

		.el-color-picker__color-inner {
			.el-icon svg {
				display: none;
			}
			border-radius: 50% !important;
			background: conic-gradient(
				from 90deg at 50% 50%,
				rgb(255, 0, 0) -19.41deg,
				rgb(255, 0, 0) 18.76deg,
				rgb(255, 138, 0) 59.32deg,
				rgb(255, 230, 0) 99.87deg,
				rgb(20, 255, 0) 141.65deg,
				rgb(0, 163, 255) 177.72deg,
				rgb(5, 0, 255) 220.23deg,
				rgb(173, 0, 255) 260.13deg,
				rgb(255, 0, 199) 300.69deg,
				rgb(255, 0, 0) 340.59deg,
				rgb(255, 0, 0) 378.76deg
			);
		}

		.el-color-picker__color {
			border-radius: 50% !important;
		}

		.el-radio-button {
			display: inline-flex;
			// max-height: 78px;
			padding: 8px;
			// border-radius: @border-radius;
			// border: 2px solid @component-border;

			// &:last-child {
			//   border-right: 2px solid transparent;
			// }

			> .el-radio-button__label {
				display: inline-flex;
			}
		}

		.el-is-checked {
			border: 2px solid red !important;
		}

		.el-form__controls-content {
			justify-content: end;
		}
	}
}
</style>
